package com.mindbook.vip.gawxchatinfo.config.shiro;

import com.mindbook.vip.gawxchatinfo.entity.user.UserBack;
import com.mindbook.vip.gawxchatinfo.mapper.user.UserBackMapper;
import com.mindbook.vip.gawxchatinfo.service.user.UserBackService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @Author wxb
 * @Datatime 2022/3/10 17:19
 * @Descript
 */
public class UserBackRealm extends AuthorizingRealm {

    @Autowired private UserBackService userBackService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("UserBackRealm授权：doGetAuthorizationInfo");

        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        authorizationInfo.addStringPermission("say:add");

        return authorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("后端认证：doGetAuthenticationInfo");
        //获取username,并判断传递过来的username是否正确
        String principal = authenticationToken.getPrincipal().toString();
        //链接数据库，发送请求获取当前用户信息
        UserBack userBackEnd = userBackService.getUserBackEndByUsername(principal);
        if(userBackEnd==null){
            throw new UnknownAccountException();
        }
        System.out.println("查询用户信息："+userBackEnd.toString());
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(userBackEnd,userBackEnd.getPassword(),"UserBackRealm");
        return authenticationInfo;
    }
}
